import xTable from "./xTable.js";
import xID from "./xID.js";
import {replaceByObj,nullObj} from "./xUtil.js";
import xUpdateModal from "./xUpdateModal.js";
import xViewModal from './xViewModal.js';
import xAlert from "./xAlert.js";
import xPanel from "./xPanel.js"
import xConfirm from "./xConfirm.js";
import xEvent from "./xEvent.js";
import xSetColsModal from "./xSetColsModal.js";

/*
   cfg
*  { el:"d1",
*     // 回调函数设置
*     cb:{
*         insert:{ function: ,param:},
*         delete:{},
*         ...,
*         queryParam: ,
*         resetParma:
*
*         requestParam:,
*         showParam;
*
*         },
*          //查询窗体设置
*         query:{
*            cols:[],
*            style:'',
*            obj:''
*         }
*         //表格设置   注意 最后一行的操作不需要设置
*         table:{
*            cols:[],
*            style:'',
*            pagenation:
*
*         }
*         // 权限设置
*         right:{ create:true,delete:true,update:true,batchDelete:true
*         }
*
*         // 更新 面板设置
*        update:{
*        }
*
*        //查看 面板设置
*        view:{
*        }
*
*  }
* */

const tmplBase = `
     	<div class="{{class}}">
			{{query}}
			<div class="crud-body">
				<div class="crud-toolbar" id="{{ctlId}}">
				   <div class="crud-toolbar-left">				   
                   </div>                  
                   <div class="crud-toolbar-right">	
                      <span class="iRefresh flat" title="刷新"></span>
                      <span class="iCsv flat" title="导出CSV"></span>
                      <span class="iXls flat" title="导出XLS"></span>
                      <span class="iSet flat" title="列设置"> </span>                  				   
                   </div>
				</div>
				<div class="crud-table" id="{{tableId}}"></div>		
			</div>			
		</div>
`;

const tmplQuery =`
<div class="crud-query">
			   <div class="crud-query-panel" id="{{queryId}}"></div>	
			   <div class="crud-query-btn">
			      <button class="btn btn-primary"   type="search">
			        <span class="iSearch">查询</span>
                  </button>
			      <button class="btn btn-primary" type="reset">
			          <span class="iReset">重置</span>
			      </button>
               </div>	
</div>
`

const tmplCreate =`<button class="btn btn-success" type="create">
                      <span class="iCreate">{{name}}</span> 
                    </button>`;
const tmplBatchDelete =`<button class="btn btn-danger" type="batchDelete">
                           <span class="iBatchDelete">批量删除</span> 
                         </button>`;

const tmplButton =`<button class="btn {{style}}" type="custom-button" index="{{index}}">
                           <span class="iconfont {{icon}}">{{name}}</span> 
                    </button>`;

export default class xCRUD {
    $root;
    vIDS = {
        queryId: xID.getID(),
        ctlId: xID.getID(),
        tableId: xID.getID()
    };
    vCfg;
    vTable;
    vViewModal;
    vQuery;
    vUpdateModal;
    vSetColsModal;
    vInitObj;

    deleteButton ={
        icon:"iDelete",
        style:'flat',
        title:'删除',
        callback: this.cbDeleteBtn.bind(this)
    }

    viewButton ={
        icon:"iView",
        style:'flat',
        title:'查看',
        callback: this.cbViewBtn.bind(this)
    }

    updateButton ={
        icon:"iEdit",
        style:'flat',
        title:'编辑',
        callback: this.cbEditBtn.bind(this)
    }

    constructor(cfg) {
        this.vCfg = cfg;
        this.$root = $('#' + cfg.el);
        let tmpl = tmplBase.replace('{{query}}',this.vCfg.query?tmplQuery:'');
        this.$root.html(replaceByObj(tmpl,{class:cfg.style||'crud',
            ...this.vIDS}));

        this.createUpdateModal();
    }


    /* 渲染区块 开始 */
    init() {
        this.initQuery();
        this.initToolbar();
        this.initTable();
        if(this.vCfg.view)
            this.initViewModal();
        if(this.vCfg.update)
            this.vUpdateModal.init();
        this.initSetColsModal();
        this.$root.on('click', 'button[type="search"]', this.evSearch.bind(this));
        this.$root.on('click', '[type="reset"]', this.evReset.bind(this));
        this.$root.on('click', '[type="create"]', this.evCreate.bind(this));
        this.$root.on('click', '[type="batchDelete"]', this.evBatchDelete.bind(this));
        this.$root.on('click', '.iRefresh', this.evRefresh.bind(this));
        this.$root.on('click', '.iCsv', this.evExportCsv.bind(this));
        this.$root.on('click', '.iXls', this.evExportXls.bind(this));
        this.$root.on('click', '.iSet', this.evSetCols.bind(this));
        this.evSearch();
    }

    initQuery(){
        if(this.vCfg.query && this.vCfg.query.cols){
              this.vQuery = new xPanel({el:this.vIDS.queryId,binds:this.vCfg.query.cols,
                  obj:this.vCfg.query.obj,style:this.vCfg.query.style});
              this.vQuery.init();
        }
    }

    initSetColsModal(){
        this.vSetColsModal = new xSetColsModal({cols:this.vTable.vOldCols,confirm:this.cbColConfirm.bind(this)});
    }

    cbColConfirm(){
        this.vTable.refresh();
    }

    initTable(){
        //注意column 配置  如果有 批量删除 必须 第一列必须为 checkbox 同时 指定 $data
        let cols = [...this.vCfg.table.cols];
        // table cols
        //action
        let actionButton = {
            title: "操作",
            type:"action",
            button:[],
            show: 2,
            fixed:"right",
            width:"10rem"
        };
        actionButton.button.push(...this.getActionButtons());
        if(actionButton.button.length>0)
            cols.push(actionButton);
        //cols.push({type:'button',title: "操作",button:this.getActionButtons(),fixed: 'right',show:2});
        if(this.vCfg.table.cols){
            this.vTable = new xTable({el:this.vIDS.tableId,cols:cols,ajax:this.vCfg.table.ajax,
                style:this.vCfg.table.style,data:this.vCfg.table.data,pagination:this.vCfg.table.pagination
            });
        }
    }

    getActionButtons(){
        let  actions =[];
        if(this.vCfg.right && this.vCfg.right.view)
            actions.push(this.viewButton);
        if(this.vCfg.right && this.vCfg.right.update)
            actions.push(this.updateButton);
        if(this.vCfg.right && this.vCfg.right.delete)
            actions.push(this.deleteButton);
        return actions;
    }

    initToolbar(){
        let rightButtons ='';
        if(this.vCfg.right){
            if(this.vCfg.right.create)
                rightButtons += tmplCreate.replace('{{name}}','新增'+(this.vCfg.CrudName||''));
            if(this.vCfg.right.batchDelete)
                rightButtons += tmplBatchDelete;
        }

        if(this.vCfg.button){
            for(let i=0;i<this.vCfg.button.length;i++){
                let tmpBtn  = this.vCfg.button[i];
                rightButtons += replaceByObj(tmplButton,{icon:tmpBtn.icon||'',
                    style:tmpBtn.style||'',name:tmpBtn.name||'',index:i});
            }
            // 增加事件处理
            let $toolbar = this.$root.find('.crud-toolbar-left');
            $toolbar.on('click','[type="custom-button"]',this.evCustomBtn.bind(this))
        }

        if(rightButtons)
            this.$root.find('.crud-toolbar-left').html(rightButtons);
    }

    initViewModal(){
        if(this.vCfg.view){
            this.vViewModal = new xViewModal({
                    ...this.vCfg.view,
                data:this.vCfg.view.cols
            });
        }

    }

    createUpdateModal(){
        if(this.vCfg.update){
            this.vInitObj = {...this.vCfg.update.obj};
            this.vUpdateModal = new xUpdateModal({
                style:this.vCfg.update.style,
                binds: this.vCfg.update.binds,
                col: this.vCfg.update.col,
                grid: 'container',
                obj: this.vCfg.update.obj,
                group:this.vCfg.update.group,
                cancle:this.cbUpdateModalCancle.bind(this)
            });
        }
    }

    cbDeleteSuccess(res){
        xAlert.success('删除成功!',2000);
        this.evSearch();
    }

    cbBatchDeleteSuccess(res){
        xAlert.success('删除成功!',2000);
        this.evSearch();
    }

    evBatchDelete(e){
        if(!this.vTable.getSelect()){
            xAlert.info('请选中需要删除的数据！',2000);
            return;
        }
        let _this = this;
        let select = this.vTable.getSelect().split(',');
        //console.log(select);
        let key = this.vTable.vCheckKey;
        let selectObj = {};
        selectObj[key] = select;
        xConfirm.pop({
            type:'error',
            content:'确认要删除'+select.length+'条数据！',
            target:$(e.currentTarget),
            placement:'right',
            confirm: () => {
                if(_this.vCfg.cb && _this.vCfg.cb.batchDelete){
                    _this.vCfg.cb.batchDelete(selectObj,_this.cbBatchDeleteSuccess.bind(_this))
                }
            },
        })
    }

    evCustomBtn(e){
         let index = e.currentTarget.getAttribute("index");
         if(this.vCfg.button[index].callback){
             this.vCfg.button[index].callback(e);
         }
    }

    evCreate(e){
        this.vUpdateModal.setCommit(this.cbCreate.bind(this));
        this.vUpdateModal.show(this.vInitObj);
    }

    evRefresh(){
        this.vTable.refresh();
    }

    evExportCsv(){
        this.vTable.exportCsv();
    }

    evExportXls(){
        this.vTable.exportXls();
    }

    evSetCols(){
        this.vSetColsModal.show();
    }

    //编辑 button 的回调函数
    cbEditBtn(item,xtable,e){
        this.vUpdateModal.setCommit(this.cbUpdate.bind(this));
        let obj = item;
        this.vUpdateModal.show(obj,'update');
    }

    // 新建 提交时 的回调
    cbCreate(){
        if(this.vCfg.cb && this.vCfg.cb.insert){
            let obj = this.vCfg.update.obj;
            this.vCfg.cb.insert(obj,this.cbCreateSuccess.bind(this),this.vUpdateModal.$root[0])
        }

    }

    // 新建 提交成功的回调函数
    cbCreateSuccess(res){
        xAlert.success('提交成功！',2000);
        xEvent.RequestOver('success',this.vUpdateModal.$root[0]);
    }

    // 编辑 提交 成功的 回调函数
    cbUpdateSuccess(res){
        xAlert.success('提交成功！',2000);
        xEvent.RequestOver('success',this.vUpdateModal.$root[0]);
    }

    cbDeleteBtn(item,xtable,e){
        let _this = this;
        if(item.children){
            xAlert.error("该节点存在下级，不能删除！");
            return ;
        }

        xConfirm.pop({
            type:'error',
            content:'确认要删除此数据！',
            target:$(e.currentTarget),
            placement:'left',
            confirm: () => {
                if(_this.vCfg.cb && _this.vCfg.cb.delete){
                    _this.vCfg.cb.delete(item,_this.cbDeleteSuccess.bind(_this))
                }
            }
        })
    }

    //编辑框 提交时，调用
    cbUpdate(){
        if(this.vCfg.cb && this.vCfg.cb.update){
            let obj = this.vCfg.update.obj;
            this.vCfg.cb.update(obj,this.cbUpdateSuccess.bind(this),this.vUpdateModal.$root[0])
        }
    }

    //编辑窗口 退出时调用
    cbUpdateModalCancle(refresh){
        if(refresh)
            this.evSearch();
    }

    cbViewBtn(item){
        this.vViewModal.show(item);
    }

    cbRetrieveSuccess(res){
        if(res.code == "200" || res.code == '210'){
            this.vTable.setData(res.data)
        } else {
            xAlert.error("查询失败");
        }
    }

    evSearch(e){
        let param ={};
        if(this.vCfg.query && this.vCfg.query.obj){
            param = this.vCfg.query.obj;
        }
        if(this.vCfg.cb) {
            this.vCfg.cb.retrieve(param,
                    this.cbRetrieveSuccess.bind(this));

            if(this.vTable.vCfg.pagination){
                this.vTable.vCfg.pagination.pageIndex = 1;
            }
        }
    }

    evReset(e){
        if(this.vCfg.cb && this.vCfg.cb.resetParma){
            this.vCfg.cb.resetParma(this.vCfg.query.obj);
        }else{
            nullObj(this.vCfg.query.obj);
        }
    }

    destroy(){
        if(this.vUpdateModal)
            this.vUpdateModal.$root.remove();
        if(this.vViewModal)
              this.vViewModal.$root.remove();
        if(this.vSetColsModal)
              this.vSetColsModal.$root.remove();
    }

    setInitObj(obj){
        this.vUpdateModal.setInitObj(obj);
    }
}